<template>
  <div class="relative w-full h-full">
    <PageHeader title="提现管理" />
    <!-- 添加分类选项 -->
    <div class="filter-tabs mb-4">
      <el-radio-group v-model="listType" @change="handleListTypeChange">
        <el-radio-button :label="'all'">全部申请</el-radio-button>
        <el-radio-button :label="'pending'">待审核</el-radio-button>
        <el-radio-button :label="'approved'">已提现</el-radio-button>
        <el-radio-button :label="'rejected'">已驳回</el-radio-button>
      </el-radio-group>
    </div>
    <SearchCom
      :searchList="searchConfig"
      @search="handleSearch"
      @reset="handleReset"
    />
    <el-table
      :data="tableData"
      style="width: 100%"
      class="cover-table mt12"
      height="calc(100% - 150px)"
      border
    >
      <el-table-column prop="applyTime" label="申请时间" width="180" />
      <el-table-column prop="withdrawName" label="提现名称" width="120" />
      <el-table-column prop="contactName" label="联系人姓名" width="120" />
      <el-table-column prop="contactPhone" label="手机号码" width="120" />
      <el-table-column prop="bankName" label="所属银行" width="120" />
      <el-table-column prop="bankCardNo" label="银行卡号" width="180" />
      <el-table-column prop="idCardNo" label="身份证号码" width="180" />
      <el-table-column prop="withdrawAmount" label="提现金额" width="120">
        <template #default="scope">
          {{ scope.row.withdrawAmount }} 元
        </template>
      </el-table-column>
      <el-table-column prop="accountBalance" label="账户余额" width="120">
        <template #default="scope">
          {{ scope.row.accountBalance }} 元
        </template>
      </el-table-column>
      <el-table-column prop="withdrawReason" label="提现原因" min-width="200" />
      <el-table-column prop="status" label="提现状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <div class="flex_aic_jcc">
            <el-button
              type="primary"
              size="small"
              @click="handleApprove(scope.row)"
              v-if="scope.row.status === 0"
            >
              通过
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleReject(scope.row)"
              v-if="scope.row.status === 0"
            >
              驳回
            </el-button>
            <!-- 添加查看驳回理由按钮 -->
            <el-button
              type="info"
              size="small"
              @click="viewRejectReason(scope.row)"
              v-if="scope.row.status === 2"
            >
              查看驳回理由
            </el-button>
            <span v-else-if="scope.row.status === 1">{{ getStatusText(scope.row.status) }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex justify-end mt24 absolute bottom-0 right-0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 驳回原因弹窗 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="驳回原因"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="rejectForm" label-width="80px" v-if="!viewMode">
        <el-form-item 
          label="驳回原因" 
          prop="reason"
          :rules="[{ required: true, message: '请输入驳回原因', trigger: 'blur' }]"
        >
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回原因"
          />
        </el-form-item>
      </el-form>
      <!-- 查看驳回理由模式 -->
      <div v-if="viewMode" class="reject-reason-view">
        <h4>驳回理由：</h4>
        <p>{{ currentWithdraw.rejectReason }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="confirmReject" v-if="!viewMode">确认驳回</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 确认提现弹窗 -->
    <el-dialog
      v-model="approveDialogVisible"
      title="确认提现"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="confirm-withdraw-info">
        <p><strong>提现申请人：</strong>{{ currentWithdraw.withdrawName }}</p>
        <p><strong>联系人：</strong>{{ currentWithdraw.contactName }}</p>
        <p><strong>提现金额：</strong>{{ currentWithdraw.withdrawAmount }} 元</p>
        <p><strong>银行卡号：</strong>{{ currentWithdraw.bankCardNo }}</p>
        <p><strong>所属银行：</strong>{{ currentWithdraw.bankName }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmApprove">确认通过</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import SearchCom from "@/components/searchCom.vue";
import PageHeader from "@/components/PageHeader.vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 列表类型
const listType = ref('all');

// 搜索配置
const searchConfig = ref([
  {
    label: "商家ID",
    key: "shopId",
    type: "input",
  },
  {
    label: "地址",
    key: "address",
    type: "input",
  },
  {
    label: "名称",
    key: "shopName",
    type: "input",
  },
  {
    label: "联系人",
    key: "contactName",
    type: "input",
  },
  {
    label: "联系电话",
    key: "contactPhone",
    type: "input",
  },
  {
    label: "用户名称",
    key: "userName",
    type: "input",
  },
  {
    label: "用户ID",
    key: "userId",
    type: "input",
  },
  {
    label: "手机号码",
    key: "userPhone",
    type: "input",
  },
  {
    label: "提现日期",
    key: "withdrawDate",
    type: "daterange",
  },
  {
    label: "提现状态",
    key: "status",
    type: "select",
    options: [
      { label: "全部", value: "" },
      { label: "待审核", value: 0 },
      { label: "已通过", value: 1 },
      { label: "已驳回", value: 2 },
    ],
  },
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100);

// 弹窗相关
const rejectDialogVisible = ref(false);
const approveDialogVisible = ref(false);
const currentWithdraw = ref({});
const rejectForm = reactive({
  reason: ""
});
const viewMode = ref(false);

// 模拟表格数据
const generateMockData = () => {
  return Array.from({ length: 10 }, (_, index) => {
    const status = index % 3; // 0: 待审核, 1: 已通过, 2: 已驳回
    
    return {
      id: index + 1,
      shopId: `SH${(index % 5 + 1).toString().padStart(3, '0')}`,
      address: `北京市朝阳区建国路${88 + index}号`,
      shopName: `商家${index % 5 + 1}`,
      contactName: `联系人${index % 5 + 1}`,
      contactPhone: `1380013${(index % 5 + 1).toString().padStart(4, '0')}`,
      userName: `用户${index + 1}`,
      userId: `UID${(10000 + index).toString()}`,
      userPhone: `1390013${index.toString().padStart(4, '0')}`,
      applyTime: `2024-${(index % 12 + 1).toString().padStart(2, '0')}-${(index % 28 + 1).toString().padStart(2, '0')} ${(index % 24).toString().padStart(2, '0')}:${(index % 60).toString().padStart(2, '0')}`,
      withdrawName: `提现申请${index + 1}`,
      bankName: ["工商银行", "建设银行", "农业银行", "招商银行", "中国银行"][index % 5],
      bankCardNo: `621700${index}${index}${index}${index}${index}${index}`,
      idCardNo: `11010119${80 + index}0101${index}${index}${index}${index}`,
      withdrawAmount: (Math.random() * 5000 + 1000).toFixed(2),
      accountBalance: (Math.random() * 10000 + 5000).toFixed(2),
      withdrawReason: ["商家运营资金周转", "员工工资发放", "设备采购", "店面装修", "原材料采购"][index % 5],
      status,
      rejectReason: status === 2 ? "银行卡信息有误，请重新提交" : ""
    };
  });
};

const allData = ref(generateMockData());

// 根据列表类型过滤数据
const tableData = computed(() => {
  if (listType.value === 'all') {
    return allData.value;
  } else if (listType.value === 'pending') {
    return allData.value.filter(item => item.status === 0);
  } else if (listType.value === 'approved') {
    return allData.value.filter(item => item.status === 1);
  } else if (listType.value === 'rejected') {
    return allData.value.filter(item => item.status === 2);
  }
  return allData.value;
});

// 处理列表类型变化
const handleListTypeChange = (value) => {
  console.log('列表类型变更为:', value);
  currentPage.value = 1;
  // 这里可以调用API重新获取数据
};

// 获取状态样式
const getStatusType = (status) => {
  const statusMap = {
    0: "warning", // 待审核
    1: "success", // 已通过
    2: "danger", // 已驳回
  };
  return statusMap[status];
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: "待审核",
    1: "已通过",
    2: "已驳回",
  };
  return statusMap[status];
};

// 处理搜索
const handleSearch = (formData) => {
  console.log("搜索条件:", formData);
  // 这里应该调用API进行搜索
  ElMessage.success("搜索请求已发送");
};

// 处理重置
const handleReset = () => {
  console.log("表单已重置");
  // 重置后可能需要重新加载初始数据
  ElMessage.info("表单已重置");
};

// 处理通过提现
const handleApprove = (row) => {
  currentWithdraw.value = row;
  approveDialogVisible.value = true;
};

// 确认通过提现
const confirmApprove = () => {
  // 这里应该调用API处理提现通过
  const index = allData.value.findIndex(item => item.id === currentWithdraw.value.id);
  if (index !== -1) {
    allData.value[index].status = 1;
    ElMessage.success("提现已通过");
    approveDialogVisible.value = false;
  }
};

// 处理驳回提现
const handleReject = (row) => {
  currentWithdraw.value = row;
  rejectForm.reason = "";
  viewMode.value = false;
  rejectDialogVisible.value = true;
};

// 查看驳回理由
const viewRejectReason = (row) => {
  currentWithdraw.value = row;
  viewMode.value = true;
  rejectDialogVisible.value = true;
};

// 确认驳回提现
const confirmReject = () => {
  if (!rejectForm.reason) {
    ElMessage.warning("请输入驳回原因");
    return;
  }
  
  // 这里应该调用API处理提现驳回
  const index = allData.value.findIndex(item => item.id === currentWithdraw.value.id);
  if (index !== -1) {
    allData.value[index].status = 2;
    allData.value[index].rejectReason = rejectForm.reason;
    ElMessage.success("提现已驳回");
    rejectDialogVisible.value = false;
  }
};

// 处理页面变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  // 这里应该调用API获取对应页的数据
};

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  // 这里应该调用API获取对应数量的数据
};
</script>

<style lang="scss" scoped>
.cover-table {
  margin-top: 20px;
}

.mt12 {
  margin-top: 12px;
}

.mt24 {
  margin-top: 24px;
}

.mb-4 {
  margin-bottom: 16px;
}

.confirm-withdraw-info {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  
  p {
    margin-bottom: 10px;
    line-height: 1.6;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.reject-reason-view {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  
  h4 {
    font-weight: bold;
    margin-bottom: 10px;
  }
  
  p {
    line-height: 1.6;
  }
}
</style>
